package com.freesky.common.utils;

import java.util.regex.Pattern;

/**
 * 密码复杂度校验工具类
 */
public class PasswordCheckUtil {

    // 密码长度最小值
    private static final int MIN_LENGTH = 8;

    // 密码长度最大值
    private static final int MAX_LENGTH = 20;

    // 密码复杂度正则表达式
    private static final String PASSWORD_PATTERN =
            "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]).{" + MIN_LENGTH + "," + MAX_LENGTH + "}$";

    /**
     * 校验密码复杂度
     *
     * @param password 密码
     * @return 校验结果
     */
    public static boolean isValidPassword(String password) {
        if (password == null) {
            return false;
        }
        return Pattern.matches(PASSWORD_PATTERN, password);
    }

    /**
     * 获取密码复杂度校验错误信息
     *
     * @param password 密码
     * @return 错误信息
     */
    public static String getPasswordValidationError(String password) {
        System.out.println("password:"+password);
        if (password == null) {
            return "密码不能为空";
        }
        if (password.length() < MIN_LENGTH) {
            return "密码长度不能小于" + MIN_LENGTH + "位";
        }
        if (password.length() > MAX_LENGTH) {
            return "密码长度不能大于" + MAX_LENGTH + "位";
        }
        if (!Pattern.matches(".*[a-z].*", password)) {
            return "密码必须包含小写字母";
        }
        if (!Pattern.matches(".*[A-Z].*", password)) {
            return "密码必须包含大写字母";
        }
        if (!Pattern.matches(".*\\d.*", password)) {
            return "密码必须包含数字";
        }
        if (!Pattern.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*", password)) {
            return "密码必须包含特殊字符";
        }
        return null;
    }
}
